package com.bsoft.gol.hcs.specialist.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.annotation.RpcService;
import com.bsoft.gol.hcs.enumcase.UserRoleEnum;
import hcn.base.Organization;
import hcn.bean.UserAllVo;
import hcn.util.ResultCode;
import org.atag.util.bbp.RoleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import pcn.service.web.BaseDeviceService;
import pcn.vo.consultation.OrgDeptDocInfo;
import service.rpc.IOrganizationRpcService;
import com.bsoft.gol.hcs.specialist.bean.request.FusHealthEducationRequest;
import com.bsoft.gol.hcs.specialist.bean.request.HealthEducationGetListReq;
import com.bsoft.gol.hcs.specialist.bean.response.*;
import com.bsoft.gol.hcs.specialist.entity.FusHealthEducationEntity;
import com.bsoft.gol.hcs.specialist.entity.FusHealthEducationRelation;
import com.bsoft.gol.hcs.specialist.service.IFusHealthEducationService;
import com.bsoft.gol.hcs.specialist.service.IHealthEducationService;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 健康宣教知识库接口实现
 *
 * @author niulei
 */
@SsdevService("healthEducation")
public class HealthEducationServiceImpl implements IHealthEducationService {
    private static final Logger logger = LoggerFactory.getLogger(HealthEducationServiceImpl.class);

    @Autowired
    IFusHealthEducationService fusHealthEducationService;

    @SsdevReference("hcn.baseDeviceService")
    private BaseDeviceService baseDeviceService;

    @Autowired
    private IOrganizationRpcService organizationRpcService;

    /**
     * 初始化健康宣教列表/得到健康宣教子列表
     *
     * @param
     * @return 健康宣教列表
     */
    @Override
    @RpcService
    public JSONArray getList(HealthEducationGetListReq getListReq) throws ControllerException {
        List<FusHealthEducationEntity> fusHealthEducationSubList = new ArrayList<>();
        //得到所有健康宣教列表
        if (null != getListReq.getFusHealthEducationId()) {
            FusHealthEducationEntity fusHealthEducationEntity = fusHealthEducationService.getFusHealthEducationById(getListReq.getFusHealthEducationId());
            fusHealthEducationSubList.add(fusHealthEducationEntity);
        } else {
            if (CommonUtils.isEmpty(getListReq.getOrganizationId())) {
                return JSONArray.parseArray("[]");
            } else {
                Organization organization = organizationRpcService.getOrgDetailByOrgCode(getListReq.getOrganizationId());
                if (null != organization) {
                    if (CommonUtils.isNotEmpty(getListReq.getDepartmentId())) {
                        fusHealthEducationSubList =
                                fusHealthEducationService.findListByOrgIdAndDepartmentId(organization.getOrgId(),
                                        getListReq.getDepartmentId());
                    } else {
                        fusHealthEducationSubList =
                                fusHealthEducationService.findFusHealthEducationSubListByOrgId(organization.getOrgId());
                    }
                }
            }
        }
        List<FusHealthEducationListResponse> fusHealthEducationList =
                resolveFusHealthEducationListResponse(fusHealthEducationSubList);
        return JSONArray.parseArray(JSON.toJSONString(fusHealthEducationList, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 根据ID列表查询健康宣教详情
     *
     * @param getListReq
     * @return com.alibaba.fastjson.JSONArray
     * @throws
     * @author tongtp
     * @date 2023/1/10 17:21
     */
    @Override
    @RpcService
    public JSONArray queryDetailByIdList(HealthEducationGetListReq getListReq) throws ControllerException {

        if (CommonUtils.isEmpty(getListReq.getEducationIdList())) {
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "传入宣教id不能为空");
        }

        List<FusHealthEducationEntity> fusHealthEducationSubList;

        //得到单条健康宣教详情
        fusHealthEducationSubList =
                fusHealthEducationService.findFusHealthEducationSubListByIdList(getListReq.getEducationIdList());

        List<FusHealthEducationListResponse> fusHealthEducationList =
                resolveFusHealthEducationListResponse(fusHealthEducationSubList);

        return JSONArray.parseArray(JSON.toJSONString(fusHealthEducationList, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 根据用户权限获取宣教列表
     *
     * @throws ControllerException
     */
    @Override
    public JSONArray getFusHealthList(HealthEducationGetListReq req) throws ControllerException {
        List<FusHealthEducationEntity> fusHealthEducationSubList;
        //1.获取当前登录用户的角色信息
        String commonRole = RoleUtils.getCurrentCommonRole();
        if (CommonUtils.isNotEmpty(req.getOrganizationId())) {
            fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByOrgId(req.getOrganizationId());
        } else {
            //机构id为空
            if (CommonUtils.isEmpty(commonRole)) {
                fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByDepartmentId(null);
            } else {
                //2.获取当前登录用户信息
                UserAllVo allByOnline = baseDeviceService.getAllByOnline();
                //3.判断当前用户是医生还是管理员
                if (UserRoleEnum.ADMIN.getRoleName().equals(commonRole)) {
                    //租户管理员，返回全部
                    if (CommonUtils.isEmpty(allByOnline.getOrgId())) {
                        fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByDepartmentId(null);
                    } else {
                        fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByOrgId(allByOnline.getOrgId());
                    }
                } else if (UserRoleEnum.DOCTOR.getRoleName().equals(commonRole)) {
                    fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByOrgId(allByOnline.getOrgId());
                } else {
                    fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByDepartmentId(null);
                }
            }
        }
        List<FusHealthEducationListResponse> fusHealthEducationList = resolveFusHealthEducationListResponse(fusHealthEducationSubList);
        return JSONArray.parseArray(JSON.toJSONString(fusHealthEducationList, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 健康宣教详情
     *
     * @param fusHealthEducationId 健康宣教Id
     * @return 健康宣教详情
     */
    @Override
    @RpcService
    public JSONArray getFusHealthEducationInfo(Long fusHealthEducationId) throws ControllerException {
        if (CommonUtils.isEmpty(fusHealthEducationId)) {
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "传入宣教id不能为空");
        }

        List<FusHealthEducationEntity> fusHealthEducationSubList;

        //得到单条健康宣教详情
        fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByIdAndType(fusHealthEducationId);

        List<FusHealthEducationListResponse> fusHealthEducationList = resolveFusHealthEducationListResponse(fusHealthEducationSubList);

        return JSONArray.parseArray(JSON.toJSONString(fusHealthEducationList, SerializerFeature.WriteMapNullValue));
    }

    private List<FusHealthEducationListResponse> resolveFusHealthEducationListResponse(List<FusHealthEducationEntity> fusHealthEducationSubList) throws ControllerException {
        List<FusHealthEducationListResponse> fusHealthEducationList = Lists.newArrayList();
        for (FusHealthEducationEntity fusHealthEducationEntity : fusHealthEducationSubList) {
            FusHealthEducationListResponse fusHealthEducationListResponse = new FusHealthEducationListResponse();
            BeanUtils.copy(fusHealthEducationEntity, fusHealthEducationListResponse);
            List<FusHealthEducationRelation> fusHealthEducationRelations =
                    fusHealthEducationService.findFusHealthEducationRelations(fusHealthEducationEntity.getFusHealthEducationId());
            fusHealthEducationListResponse.setAssociatedDiseases(fusHealthEducationRelations);
            //查询localOrgId即organizationId
            if (CommonUtils.isNotEmpty(fusHealthEducationEntity.getOrgId())) {
                Organization organization =
                        organizationRpcService.getOrgDetailByOrgId(fusHealthEducationEntity.getOrgId());
                if (organization != null) {
                    fusHealthEducationListResponse.setOrganizationId(organization.getLocalOrgId());
                }
            }
            fusHealthEducationList.add(fusHealthEducationListResponse);
        }
        return fusHealthEducationList;
    }


    /**
     * 递归查询出所有的子目录
     *
     * @param fusHealthEducationId 健康宣教id
     * @param floor                层级
     * @return 子目录
     */
    private JSONArray getFusHealthEducationSubList(Long fusHealthEducationId, int floor) throws ControllerException {
        int nextFloor = floor + 1;
        JSONArray jsonArray = new JSONArray();
        List<FusHealthEducationEntity> fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByIdAndType(fusHealthEducationId);
        if (fusHealthEducationSubList != null && fusHealthEducationSubList.size() > 0) {
            for (FusHealthEducationEntity fusHealthEducation : fusHealthEducationSubList) {
                FusHealthEducationResp fusHealthEducationResp = new FusHealthEducationResp();
                BeanUtils.copy(fusHealthEducation, fusHealthEducationResp);
                String fileListStr = fusHealthEducation.getFileList();
                List<FileBean> fileBeanList = new ArrayList<>();
                if (!StringUtils.isEmpty(fileListStr)) {
                    fileBeanList = JSONObject.parseArray(fileListStr, FileBean.class);
                }
                fusHealthEducationResp.setFileBeanList(fileBeanList);
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(fusHealthEducationResp, SerializerFeature.WriteMapNullValue));
                JSONArray subList = this.getFusHealthEducationSubList(fusHealthEducation.getFusHealthEducationId(), nextFloor);
                if (subList.size() > 0) {
                    jsonObject.put("subList", subList);
                }
                //当前目录层数
                jsonObject.put("floor", floor);
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }

    /**
     * 保存/修改健康宣教内容
     *
     * @param healthEducationRequest 健康宣教内容
     */
    @Override
    @RpcService
    public void save(FusHealthEducationRequest healthEducationRequest) throws ControllerException {
        if (CommonUtils.isNull(healthEducationRequest.getName())) {
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "传入参数不能为空");
        }
        saveFusHealthEducation(healthEducationRequest);

    }


    /**
     * 根据ID是否为空判断是否是新增还是更新，并执行保存
     *
     * @param
     */
    private void saveFusHealthEducation(FusHealthEducationRequest fusHealthEducationRequest) throws ControllerException {
        FusHealthEducationEntity fusHealthEducation = new FusHealthEducationEntity();
        BeanUtils.copy(fusHealthEducationRequest, fusHealthEducation);

        if (CommonUtils.isEmpty(fusHealthEducationRequest.getOrganizationId())) {
            throw new ControllerException("机构代码不能为空");
        }
        Organization organization = organizationRpcService.getOrgDetailByOrgCode(fusHealthEducationRequest.getOrganizationId());
        if (null == organization) {
            throw new ControllerException("机构不存在");
        }
        fusHealthEducation.setOrgId(organization.getOrgId());

        Long fusId;
        Date now = new Date();
        //新增
        if (CommonUtils.isNull(fusHealthEducationRequest.getFusHealthEducationId())) {
            fusHealthEducation.setGmtCreate(now);
            FusHealthEducationEntity save = fusHealthEducationService.insertFusHealthEducation(fusHealthEducation);
            fusId = save.getFusHealthEducationId();
        } else {//修改
            fusHealthEducation.setGmtModified(now);
            fusHealthEducationService.updateFusHealthEducationById(fusHealthEducation);
            fusId = fusHealthEducation.getFusHealthEducationId();
            //删除关联病种
            fusHealthEducationService.deleteHealthEducationRelationByFusHealthEducationId(fusHealthEducation.getFusHealthEducationId());
        }

        //关联疾病处理
        List<FusHealthEducationRelation> fusHealthEducationRelationList = fusHealthEducationRequest.getAssociatedDiseases();

        for (FusHealthEducationRelation fusHealthEducationRelation : fusHealthEducationRelationList) {
            fusHealthEducationRelation.setFusHealthEducationId(fusId);
            fusHealthEducationService.insertFusHealthEducationRelation(fusHealthEducationRelation);
        }
    }


    /**
     * 删除健康宣教目录/材料
     *
     * @param fusHealthEducationId 健康宣教入参
     */
    @Override
    @RpcService
    public void delete(Long fusHealthEducationId) throws ControllerException {
        if (CommonUtils.isNull(fusHealthEducationId)) {
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "传入宣教id不能为空");
        }
        //删除当前宣教目录或内容
        fusHealthEducationService.deleteFusHealthEducationById(fusHealthEducationId);
        //删除关联病种
        fusHealthEducationService.deleteHealthEducationRelationByFusHealthEducationId(fusHealthEducationId);


    }

    /**
     * 删除健康宣教材料
     *
     * @param fusHealthEducationId 健康宣教Id
     * @return 健康宣教内容
     */
    @Override
    @RpcService
    public FusHealthEducationResp getFusHealthEducationContent(Long fusHealthEducationId) throws ControllerException {
        FusHealthEducationResp fusHealthEducationResp = new FusHealthEducationResp();
        FusHealthEducationEntity fusHealthEducationEntity = fusHealthEducationService.getFusHealthEducationContent(fusHealthEducationId);
        BeanUtils.copy(fusHealthEducationEntity, fusHealthEducationResp);
        String fileListStr = fusHealthEducationEntity.getFileList();
        List<FileBean> fileBeanList = new ArrayList<>();
        if (!StringUtils.isEmpty(fileListStr)) {
            fileBeanList = JSONObject.parseArray(fileListStr, FileBean.class);
        }
        fusHealthEducationResp.setFileBeanList(fileBeanList);
        return fusHealthEducationResp;
    }

    /**
     * 根据医生ID查询健康宣教列表
     *
     * @param diseasesAndFusListResp
     */
    @Override
    public List<FusHealthEducationByDortorResponse> findFusHealthEducationByDoctorId(DiseasesAndFusListResp diseasesAndFusListResp) throws ControllerException {
        List<FusHealthEducationByDortorResponse> responseList = new ArrayList<>();
        List<OrgDeptDocInfo> orgDeptDocInfoList;
        List<OrgDeptDocInfo> resOrgDeptDocInfoList = new ArrayList<>();
        try {
            orgDeptDocInfoList = (List<OrgDeptDocInfo>) Client.rpcInvoke("hcn.orgDoctors", "queryOrgDeptDocInfo", diseasesAndFusListResp.getDoctorId());
            if (CommonUtils.isNotEmpty(orgDeptDocInfoList)) {
                resOrgDeptDocInfoList = orgDeptDocInfoList.stream().filter(orgDeptDocInfo -> orgDeptDocInfo.getOrgId().equals(diseasesAndFusListResp.getOrganizationId())).collect(Collectors.toList());
            }

            for (OrgDeptDocInfo orgDeptDocInfo : resOrgDeptDocInfoList) {
                FusHealthEducationByDortorResponse fusHealthEducationByDortorResponse = new FusHealthEducationByDortorResponse();
                //赋值
                fusHealthEducationByDortorResponse.setOrganizationId(orgDeptDocInfo.getOrgId());
                fusHealthEducationByDortorResponse.setDepartmentId(orgDeptDocInfo.getLocalDeptId());
                fusHealthEducationByDortorResponse.setDepartmentName(orgDeptDocInfo.getDeptName());
                //根据科室id获取健康宣教列表
                List<FusHealthEducationEntity> fusHealthEducationSubList = fusHealthEducationService.findFusHealthEducationSubListByDepartmentId(orgDeptDocInfo.getLocalDeptId());

                List<HealthEducationList> healthEducationList = new ArrayList<>();

                for (FusHealthEducationEntity fusHealthEducationSub : fusHealthEducationSubList) {
                    HealthEducationList healthEducation = new HealthEducationList();
                    BeanUtils.copy(fusHealthEducationSub, healthEducation);
                    healthEducationList.add(healthEducation);
                }
                fusHealthEducationByDortorResponse.setHealthEducationList(healthEducationList);
                responseList.add(fusHealthEducationByDortorResponse);
            }
        } catch (Exception e) {
            logger.error("查询医生职业点失败：" + e.getMessage());
            throw new ControllerException("查询医生职业点失败");
        }
        return responseList;
    }

    /**
     * 根据病种id查病健康宣教列表
     *
     * @param diseaseTypeId
     */
    @Override
    public List<HealthEducationList> findDiseaseTypeListByDiseId(Long diseaseTypeId) throws ControllerException {
        if (CommonUtils.isEmpty(diseaseTypeId)) {
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "传入病种id不能为空");
        }
        return fusHealthEducationService.findDiseaseTypeListByDiseeId(diseaseTypeId);
    }
}
